package com.yy.example.security;

import com.yy.example.bean.Permission;
import com.yy.example.bean.Role;
import com.yy.example.bean.User;
import com.yy.example.dao.PermissionDao;
import com.yy.example.dao.RoleDao;
import com.yy.example.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yangyibo on 17/2/7.
 */
@Service
public class UrlUserService implements UserDetailsService {
    @Autowired
    UserDao userDao;
    @Autowired
    PermissionDao permissionDao;
    @Autowired
    RoleDao roleDao;

    @Override
    public UserDetails loadUserByUsername(String userName) { //重写loadUserByUsername 方法获得 userdetails 类型用户

        User user = userDao.findByUsername(userName);
        if (user != null) {
            List<Role> role = user.getRole();

            // List<Integer> collect = role.stream().map(val -> val.getId()).collect(Collectors.toList());
            //  List<Role> roles = roleDao.findAllById(collect);

            List<Permission> permissions = new ArrayList<>();
            role.forEach(val -> permissions.addAll(val.getPermissions()));
            // List<Permission> permissions = permissionDao.findByUser(user.getId());
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            for (Permission permission : permissions) {
                if (permission != null && permission.getName() != null) {
                    GrantedAuthority grantedAuthority = new UrlGrantedAuthority(permission.getPermissionUrl(), permission.getMethod());
                    grantedAuthorities.add(grantedAuthority);
                }
            }
            user.setAuthorities(grantedAuthorities);
            return user;
        } else {
            throw new UsernameNotFoundException("admin: " + userName + " do not exist!");
        }
    }
}